#!/usr/bin/env python
import sys, os, json
import Modules.ChomsPy.DAD as DAD
import Modules.Pygmund.Id as Id
from Modules.Pygmund.Utilities import AddSep

h = """\
Initialize ChomsPy Database

description:
	Manage ChomsPy Database.
	
usage:
	$ ./chomspy.py pragmatic [user password [data.json]]
		pragmatic = Pragmatic string
		user, password = User Credentials (optional, as needed)
		data.json = Path to JSON file with data to save (optional, as needed)
		
examples:
	$ ./chomspy.py "Test/Get/sample.data"
	$ ./chomspy.py "Test/Set/sample.data,update" admin admin sample.json
	
"""

try:
	if sys.argv[1] == "help" or sys.argv[1] == "h":
		print h
	else:
		if len(sys.argv) < 2 or len(sys.argv) > 5:
			print h + "\n" + "Error: Invalid parameters.\n"
		elif len(sys.argv) == 2:
			c = sys.argv[1]
			db = DAD.Connect(Id.Init("id/cognition.conf").Get("CHOMSPY"), "", "")
			print json.dumps(db.Command(c), indent=4)
			
		else:
			c = sys.argv[1]
			u = sys.argv[2]
			p = sys.argv[3]
			db = DAD.Connect(Id.Init("id/cognition.conf").Get("CHOMSPY"), u, p)
			if c == "init":
				# Initialize Database...
				c = "Test/Set/post.first"
				d = { "data" : "Database Initialized!" }
				print json.dumps(db.Command(c, d), indent=4)
				
			elif len(sys.argv) == 5:
				try:
					f = open(sys.argv[4], "rb")
					d = json.load(f)
					f.close()
					print json.dumps(db.Command(c, d), indent=4)
				except OSError, e:
					print json.dumps({ "error" : e.strerror }, indent=4)
			else:
				print json.dumps(db.Command(c), indent=4)

except IndexError, e:
	print h
